<?php

namespace app\util;

use Overtrue\Pinyin\Pinyin;
use think\Db;
use think\Log;

/*
 * 常用方法
 */
class Utils
{
    /*
     * 返回json数据
     */
    public static function ajaxReturn($code, $msg, $data)
    {
        $return = [
            'code' => $code,
            'msg' => $msg,
            'data' => $data
        ];

        return json_encode($return);
    }
    
    /*
     * 返回数组数据
     */
    public static function H5Return($code, $msg, $data)
    {
        $return = [
            'code' => $code,
            'msg' => $msg,
            'data' => $data
        ];

        return $return;
    }

    /*
     * 发送短信
     */
    public static function sendSms($mobile, $content)
    {
        /*
        $sms = new ChuanglanSms();

        $result = $sms->sendSMS($mobile, $content,'true');
        $result = $sms->execResult($result);

        $sendResult = [];

        if (isset($result[1])) {
            if ($result[1] == 0) {
                $sendResult = [
                    'code' => 'success',
                    'msg' => '发送成功',
                ];
            } else {
                $errorMsg = [
                    '0' =>'发送成功',
                    '101'=>'无此用户',
                    '102'=>'密码错',
                    '103'=>'提交过快',
                    '104'=>'系统忙',
                    '105'=>'敏感短信',
                    '106'=>'消息长度错',
                    '107'=>'错误的手机号码',
                    '108'=>'手机号码个数错',
                    '109'=>'无发送额度',
                    '110'=>'不在发送时间内',
                    '111'=>'超出该账户当月发送额度限制',
                    '112'=>'无此产品',
                    '113'=>'extno格式错',
                    '115'=>'自动审核驳回',
                    '116'=>'签名不合法，未带签名',
                    '117'=>'IP地址认证错',
                    '118'=>'用户没有相应的发送权限',
                    '119'=>'用户已过期',
                    '120'=>'内容不是白名单',
                ];

                $sendResult = [
                    'code' => 'error',
                    'msg' => $errorMsg[$result[1]],
                ];
            }
        } else {
            $sendResult = [
                'code' => 'error',
                'msg' => '发送短信错误',
            ];
        }

        return $sendResult;
        */

//        $sms = new ChuanglanSmsApi();
//        $result = $sms->sendSMS($mobile, $content, 'true');
//
//        $sendResult = [];
//
//        if (!is_null(json_decode($result))) {
//            $output = json_decode($result,true);
//            if (isset($output['code']) && $output['code'] == '0') {
//                $sendResult = [
//                    'code' => 'success',
//                    'msg' => '发送成功',
//                ];
//            } else {
//                $sendResult = [
//                    'code' => 'error',
//                    'msg' => $output['errorMsg'],
//                ];
//            }
//        } else {
//            $sendResult = [
//                'code' => 'error',
//                'msg' => '发送短信错误',
//            ];
//        }
        $sendResult = [
                    'code' => 'success',
                    'msg' => '发送成功',
                ];
        return $sendResult;
    }

    /*
     * 发送服务消息
     */
    public static function sendServicenews($titleid, $otherid, $yuyue_id, $content, $userid, $type, $store_id, $umengData,$sound='')
    {
        $data = [
            'titleid' => $titleid,
            'otherid' => $otherid,
            'yuyue_id' => $yuyue_id,
            'content' => $content,
            'add_time' => time(),
            'userid' => $userid,
            'type' => $type,
            'store_id' => $store_id
        ];

        $result = Db::name('servicenews')->insert($data);
        if ($result) {
            $umeng =  new Umeng();

            $result = $umeng->sendAndroidCustomizedcast($umengData['title'], $umengData['content'], $umengData['alias_type'], $umengData['alias'],'', '', false,$sound);
            $result = $umeng->sendIOSCustomizedcast($umengData['content'], $umengData['alias_type'], $umengData['alias'], '', '', false,$sound);
        } else {
            Log::log('发送服务消息错误');
        }
    }

    /*
     * 生成资金流水号
     */
    public static function generateFlowNumber($telephone)
    {
        $flowNumber = $telephone . time() . mt_rand(1000, 9999);

        $exist = Db::name('moneyflow')
            ->where('flow_number', '=', $flowNumber)
            ->order('add_time desc')
            ->find();
        if (is_null($exist)) {
            return $flowNumber;
        } else {
            self::generateFlowNumber($telephone);
        }
    }

    /*
     * 生成订单号
     */
    /*
    public static function generateOrdNum($telephone, $type)
    {
        $ordNum = $type . $telephone . time() . mt_rand(1000, 9999);

        $exist = Db::name('order')
            ->where('ord_num', '=', $ordNum)
            ->order('add_time desc')
            ->find();
        if (is_null($exist)) {
            return $ordNum;
        } else {
            self::generateOrdNum($telephone, $type);
        }
    }
    */

    /*
     * 生成订单号
     */
    public static function generateOrdNum($type, $ordtype, $ctm_id)
    {
        $ctmLength = 3;

        $length = strlen($ctm_id);
        if ($length == $ctmLength) {
            $ctm_id = $ctm_id;
        } else if ($length < $ctmLength) {
            $lastLength = $ctmLength - $length;
            $string = '';
            for ($i = 0; $i < $lastLength; $i++) {
                $string = $string . '0';
            }
            $ctm_id = $string . $ctm_id;
        } else if ($length > $ctmLength) {
            $ctm_id = substr($ctm_id, -3);
        }

        $ordNum = $type . $ordtype . substr(time(), 2) . $ctm_id . mt_rand(0, 9);

        $exist = Db::name('order')
            ->where('ord_num', '=', $ordNum)
            ->order('add_time desc')
            ->find();
        if (is_null($exist)) {
            return $ordNum;
        } else {
            self::generateOrdNum($type, $ordtype, $ctm_id);
        }
    }

    /*
     * 通过CURL发送HTTP请求
     * @param string $url 请求URL
     * @param array $postFields 请求参数
     */
    public static function curlPost($url, $postFields) {
        $postFields = http_build_query($postFields);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }

    /*
     * 通过CURL发送HTTP请求
     */
    public static function curlSSLPost($url, $postFields) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }

    /*
     * 通过CURL发送GET请求
     */
    public static function curlGet($url)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }

    /*
     * 通过CURL发送GET请求
     */
    public static function curlSSLGet($url)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_URL, $url);
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }

    /*
     * 生成token
     */
    public static function generateToken()
    {
        $string = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $length = strlen($string);

        $rand = '';
        for ($i = 0; $i < 32; $i++) {
            $start = mt_rand(0, $length - 1);
            $char = substr($string, $start, 1);

            $rand = $rand . $char;
        }

        return md5($rand);
    }

    /*
     * 验证token
     * $app_id = 1 商户版
     * $app_id = 2 用户版
     */
    public static function verifyToken($user_id, $userAgent, $app_id = 1)
    {
        //user-agent样式
        //Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.79 Safari/537.36 token=1234567890
		
		return true;

        $pos = strpos($userAgent, 'token');
        if ($pos === false) {
            return false;
        } else {
            $token = substr($userAgent, $pos + 6);

            if ($app_id == 1) {
                $staffRow = Db::name('staff')->where('id', '=', $user_id)->field('token')->find();
                if (!is_null($staffRow) && $staffRow['token'] == $token) {
                    return true;
                } else {
                    return false;
                }
            } else if ($app_id == 2) {
                $customRow = Db::name('custom')->where('id', '=', $user_id)->field('token')->find();
                if (!is_null($customRow) && $customRow['token'] == $token) {
                    return true;
                } else {
                    return false;
                }
            }
        }
    }

    /*
     * 生成签名
     * 加密$array中务必包含appkey
     */
    public static function sign($array)
    {
        ksort($array);
        $string = "";
        while (list($key, $val) = each($array)) {
            $string = $string . $key . '=' . $val . '&';
        }
        $string = substr($string, 0, strlen($string) - 1);
        return md5($string);
    }

    /*
     * 验证签名
     */
    public static function verifySign($appkey, $array)
    {
        $newarray = array();
        $newarray["appkey"] = $appkey;
        reset($array);
        while (list($key, $val) = each($array)) {
            if ($key != "sign") {
                $newarray[$key] = $val;
            }
        }
        $sign = self::sign($newarray);
        if ($sign == $array["sign"]) {
            return true;
        }
        return false;
    }

    /*
     * 验证手机号有效性
     */
    public static function checkTelephone($telephone)
    {
        $pattern = '/^1\d{10}$/';

        return preg_match($pattern, $telephone);
    }

    /*
     * 返回字符串第一个字母的大写
     */
    public static function getFirstChar($string)
    {
        $firstChar = '#';

        $array = [
            'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
            'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
        ];

        $pinyin = new Pinyin();

        $abbr = $pinyin->abbr($string);
        $firstChar = substr($abbr, 0, 1);
        if (in_array($firstChar, $array)) {
            $firstChar = strtoupper($firstChar);
        }

        return $firstChar;
    }

    /*
     * 返回变色后的消息
     */
    public static function getColoredString($content)
    {
        $content = str_replace("[", "<font color='#333333'>", $content);
        $content = str_replace("]", "</font>", $content);

        return $content;
    }

    /*
     * 返回推送消息
     */
    public static function getPushString($content)
    {
        $content = str_replace("[", "", $content);
        $content = str_replace("]", "", $content);

        return $content;
    }
    
    /*
     *微信二次分享      
     */
    public static function Wxshare($pic,$title,$description,$currentUrl){
        $data = array(
        'pic'=>$pic,//图片地址
        'title'=>$title,//标题
        'description'=>$description//描述
        );
        $weixinmodel = new Wxshare();
        $weixindata = array();
        $weixindata['appId'] = Wxshare::APPID;//appid
        $weixindata['nonceStr'] = $weixinmodel->createNonceStr();
        $weixindata['timestamp'] = time();

        //$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
        $url = $currentUrl;
        $weixindata['pic'] = $data['pic'];
        $weixindata['link'] = $url;
        $weixindata['title'] = $data['title'];
        $weixindata['description'] = mb_substr($data['description'], 0, 30, 'UTF-8');
        $weixindata['signature'] = $weixinmodel->signature($weixindata['nonceStr'],$weixindata['timestamp'],$url);
        return $weixindata;
    }


}